package com.example.task;

import com.example.model.pojo.Competition;
import com.example.service.CompetitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description //TODO
 * @Date 2022/9/20
 * @Author cxy
 **/
@Component
public class KillTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompetitionService competitionService;

    @Scheduled(cron = "0/2 * * * * *")
    public void CompetitionTask() {
        List<Competition> list = competitionService.findAll();
        if (null != list && list.size() > 0) {
            ListOperations lop = redisTemplate.opsForList();
            for (Competition c : list) {
                if (lop.size("c_" + c.getId()) == 0) {
                    redisTemplate.opsForValue().set("c_status_" + c.getId(), "0");
                    Integer n = c.getNum();
                    for (int i = 0; i < n; i++) {
                        lop.leftPush("c_" + c.getId(), c.getId());
                    }
                }
            }
        }
    }

    @Scheduled(cron = "0/2 * * * * *")
    public void activeTask() {
        List<Integer> list = competitionService.findActiveIds();
        if(null!=list&&list.size()>0){
            System.out.println(">>>竞赛报名已经开始了<<<");
            for (Integer id :list){
                redisTemplate.opsForValue().set("c_status_"+id,"1");
            }
        }
    }

    @Scheduled(cron = "0/2 * * * * *")
    public void endTask() {
        List<Integer> list = competitionService.findEndIds();
        if(null!=list&&list.size()>0){
            System.out.println(">>>竞赛报名已经结束了<<<");
            for (Integer id :list){
                redisTemplate.opsForValue().set("c_status_"+id,"2");
            }
        }
    }
}